package com.tedu.egspringbootmvc.exception;


import com.tedu.egspringbootmvc.result.JsonResult;
import com.tedu.egspringbootmvc.result.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GloabalException {
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String message=e.getFieldError().getDefaultMessage();
        log.error(message, e);


        return new JsonResult(StatusCode.VALIDATED_ERROR,message);
    }

    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException e) {
        String message=e.getMessage();
        message=message.substring(message.indexOf(":")+1).trim();
        log.error(message, e);
        return new JsonResult(StatusCode.VALIDATED_ERROR,message);
    }

}
